// Generator 配合 Promise 的异步方案

function ajax (url) {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest()
    xhr.open('GET', url)
    xhr.responseType = 'json'
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response)
      } else {
        reject(new Error(xhr.statusText))
      }
    }
    xhr.send()
  })
}

function * main () {
  try {
    const users = yield ajax('/api/users.json')
    console.log('users:', users)

    const posts = yield ajax('/api/posts.json')
    console.log('posts:', posts)

    const urls1 = yield ajax('/api/utls111.json')
    console.log('urls1:', urls1)

    const urls2 = yield ajax('/api/utls.json')
    console.log('urls2:', urls2)
  } catch (err) {
    console.log('err:', err)
  }
}

// 通过递归来实现异步调用
function co (generator) {
  const g = generator();

  function handleResult (result) {
    if (result.done) {
      return
    }
    result.value.then(data => {
      handleResult(g.next(data))
    }).catch(err => {
      // 添加错误处理
      g.throw(new Error(err))
    })
  }

  handleResult(g.next())
}

co(main)

// Generator 配合 Promise 实现类似同步写法的异步效果

// const g = main();
// const result = g.next()
// result.value.then(data => {
//   const result2 = g.next(data)
//   if (result2.done) {
//     return
//   }
//   result2.value.then(data => {
//     const result3 = g.next(data)
//     if (result3.done) {
//       return
//     }
//     g.next(data)
//   })
// })
